package com.xp.record25.bio.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class NewNioServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8888));
        ByteBuffer buffer = ByteBuffer.allocate(16);

        List<SocketChannel> clients =  new ArrayList<>();
        while (true) {
//            System.out.println("等待链接。。。。。。");
            SocketChannel sc = ssc.accept();
            if (sc!=null) {
                clients.add(sc);
                sc.configureBlocking(false);
                System.out.println("已连接。。。。。。" + sc);
            }

            if (!clients.isEmpty()) {
                for (SocketChannel client : clients) {
                    int read = client.read(buffer);
                    if (read > 0) {
                        buffer.flip();
                        System.out.println("接收到消息+"+new String(buffer.array()));
                        buffer.clear();
                    }
                }
            }
        }
    }
}
